package org.forum.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.forum.domain.User;
import org.forum.domain.ViceTopic;
import org.forum.service.UserService;
import org.forum.service.ViceTopicService;
import org.forum.utils.JsonUtil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 话题相关模块
 * 功能：
 * 1、查找论坛每一层的信息（包括用户信息、层主的言论信息）
 * 2、查找每一层的回复相关信息
 * 
 * @author One
 *
 */
public class ViceTopicController {
	
	Logger logger = LoggerFactory.getLogger(ViceTopicController.class);
	//spring 注入
	private ViceTopicService viceTopicService;

	public void setViceTopicService(ViceTopicService viceTopicService) {
		this.viceTopicService = viceTopicService;
	}
	
	private UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	private JsonUtil jsonUtil;

	public void setJsonUtil(JsonUtil jsonUtil) {
		this.jsonUtil = jsonUtil;
	}

	//strut注入
	private int mainTopicId;

	public void setMainTopicId(int mainTopicId) {
		this.mainTopicId = mainTopicId;
	}





	/**
	 * 根据话题id返回多个层的信息
	 * 交互方式：ajax
	 * 输入：forumId
	 * 处理：
	 * 1、得到所有ViceTopic（按时间排序）
	 * 2、得到所有的UserInfo
	 * 3、通过json发送出去
	 * 输出：json数据
	 * @param mainTopicId
	 */
	public void getViceTopicInfo(int mainTopicId){
		int pageSize=3;
		int pageNo_4=0;
		HttpServletRequest request = ServletActionContext.getRequest();
		if(request.getSession().getAttribute("pageNo_4") != null){
			pageNo_4 = (int) request.getSession().getAttribute("pageNo_4");
		}
		//得到所有的viceTopics
		List<ViceTopic> viceTopics = viceTopicService.getViceTopicsByMainTopicId(mainTopicId, pageNo_4, pageSize);
		Map<String, String> userIds = new HashMap<>();
		Iterator<ViceTopic> iter = viceTopics.iterator();
		while(iter.hasNext()){
			ViceTopic viceTopic = iter.next();
			userIds.put( "" + viceTopic.getViceTopicId(),"" +  viceTopic.getPublisherId());
		}
		//获取所有的User
		//主键：viceTopicId，值：User
		Map<String, User> users = userService.getUserInfoByIds(userIds);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("viceTopics", viceTopics);
		jsonObject.put("userInfos", users);
		
		jsonUtil.outToJsonString(jsonObject.toString());
		
	}
	
	
}
